import request from '@/router/axios';

const qiniu = require('qiniu-js');
const uploadFileToOSS = (file, fileName = '', callBack, progressCB = null) => {
  return new Promise((resolve, reject) => {
    const name = fileName === '' ? file.name : fileName;
    request({
      url: 'qiniu/getToken',
      method: 'get',
    }).then(result => {
      if (result.data.code === 200) {
        const observer = {
          next(res) {
            console.log('next: ', res);
            if (progressCB !== null) {
              progressCB(res.total.percent);
            }
          },
          error(err) {
            console.log(err);
            reject(err.message);
          },
          complete(res) {
            console.log('complete: ', res, resolve);
            // progressCB(100);
            callBack(process.env.VUE_APP_OSS_REGION + '/' + res.key);
            resolve(process.env.VUE_APP_OSS_REGION + '/' + res.key);
          }
        };
        const observable = qiniu.upload(file, name, result.data.data);
        // eslint-disable-next-line no-unused-vars
        const subscription = observable.subscribe(observer); // 上传开始
      }
    }).catch(() => {
      this.$Message.error('获取上传 token 失败');
    });
  });
};

export default uploadFileToOSS;
